package com.yueban.util;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Guan on 2017/4/26.
 */

public class OkHttpUtil {
    private static OkHttpClient httpClient;

    private static synchronized void setHttpClientInstance() {
        if(httpClient == null){
            httpClient = new OkHttpClient();
        }
    }

    //获取okhttp客户端单例
    private static OkHttpClient getHttpClientInstance() {
        if (httpClient == null) {
            setHttpClientInstance();
        }
        return httpClient;
    }

    //含参含文件post方法
    public static Response doPost(String url, HashMap<String, String> params, String fileKey, List<File> files) throws IOException {
        return getPostResult(getHttpClientInstance(), url, buildMultipartBody(params, fileKey, files));
    }

    //含参数无文件post方法
    public static Response doPost(String url, HashMap<String, String> params) throws IOException {
        return getPostResult(getHttpClientInstance(), url, buildFormBody(params));
    }

    //构造表单体
    private static FormBody buildFormBody(HashMap<String, String> params) {
        okhttp3.FormBody.Builder builder = new okhttp3.FormBody.Builder();
        if (params != null) {
            for (HashMap.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        return builder.build();
    }

    //构造复杂表单体
    private static MultipartBody buildMultipartBody(HashMap<String, String> params, String fileKey, List<File> files) {
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);

        if (params != null) {
            for (HashMap.Entry<String, String> entry : params.entrySet()) {
                multipartBodyBuilder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }
        //遍历paths中所有图片绝对路径到builder，并约定key作为后台接受多张图片的key
        if (files != null) {
            for (File file : files) {
                multipartBodyBuilder.addFormDataPart(fileKey, file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
            }
        }
        return multipartBodyBuilder.build();
    }

    //执行请求，获取返回结果
    private static Response getPostResult(OkHttpClient mhttpClient, String url, RequestBody requestBody) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return mhttpClient.newCall(request).execute();
    }
}
